# Gilardi, Fabrizio, "The Temporary Importance of Role Models for Women's Political Representation", American Journal of Political Science
# Code to replicate Figure SI2 (Election rate of female and male candidates, 1970-2010)
# gilardi@ipz.uzh.ch, 2014-06-24

# Set working directory
setwd("../Data/")

# Load data
d <- read.csv("dataset-full.csv")

# Vector of election years
y <- seq(1970, 2010, 4)

# Empty matrix to store election rates 
men <- women <- cbind(y, NA, NA, NA, NA)
colnames(men) <- colnames(women) <- c("year", "mean", "se", "ciinf", "cisup")


# Compute election rates and confidence intervals

for(i in 1:length(y)){

	ratio.w <- d$n.women.elected[d$n.women.cand > 0 & d$year==y[i]]/d$n.women.cand[d$n.women.cand > 0 & d$year==y[i]]
	out.w <- lm((ratio.w*100) ~ 1)
	women[i,2] <- summary(out.w)$coefficients[1]
	women[i,3] <- summary(out.w)$coefficients[2] 

	ratio.m <- d$n.men.elected[d$n.men.cand > 0 & d$year==y[i]]/d$n.men.cand[d$n.men.cand > 0 & d$year==y[i]]
	out.m <- lm(I(ratio.m*100) ~ 1)
	men[i,2] <- summary(out.m)$coefficients[1]
	men[i,3] <- summary(out.m)$coefficients[2] 	
	
}

men <- as.data.frame(men)
women <- as.data.frame(women)

men$cisup <- men$mean + qnorm(0.95)*men$se
men$ciinf <- men$mean - qnorm(0.95)*men$se

women$cisup <- women$mean + qnorm(0.95)*women$se
women$ciinf <- women$mean - qnorm(0.95)*women$se


# Figure

a <- 0.5
#pdf(file="Figure-SI2.pdf", paper="special", width=7.5, height=5.5)
par(mar=c(3.6,3.5,2,1), mgp=c(2.5,0.8,0), cex.axis=1.2, cex.lab=1.2, font.main=1)
plot(range(y), c(0, range(c(men[,-c(1,3)], women[,-c(1,3)]))[2]), type="n", ylab="Success rate", xlab="Election year", axes=F)
axis(2)
axis(1, at=y)
points(y-a, men$mean, cex=1.5)
segments(y-a, men$ciinf, y-a, men$cisup)
points(y+a, women$mean, cex=1.5, pch=16)
segments(y+a, women$ciinf, y+a, women$cisup)
legend("bottomright", pch=c(1,16), c("Male candidates", "Female candidates"), pt.cex=1.5, cex=1.2, bty="n")
#dev.off()

